import axios, { type AxiosResponse } from 'axios'
import {warningMessage} from "@/utils/message";
import type { HttpResponse, ServerResponse } from '@/class/HttpResponse';

const selfInterceptorsResponse = function (response: AxiosResponse<ServerResponse<any>>): AxiosResponse<ServerResponse<any>> | Promise<AxiosResponse<ServerResponse<any>>> {
    if (requestIsSuccess(response)) {
        return response;
    } else {
        warningMessage(requestGetServerMessage(response));
        return response;
    }
};
const selfInterceptorsError=function (error:any){
    // warningMessage(this,error.message)
    // alert(error.message)
    warningMessage(requestGetError(error))
    return error.response;
}
//定义返回值类型
export type MyResponse<T> = Promise<AxiosResponse<ServerResponse<T>>>

const requests = async <T>(config?: any) => {
    const myRequest = axios.create({
        baseURL: 'api',
    });
    myRequest.interceptors.response.use(selfInterceptorsResponse,selfInterceptorsError)
    let result = await( myRequest(config) as MyResponse<T>)
    return result.data
};

const requestsLongtime = async <T>(config?: any) => {
    const myRequest = axios.create({
        baseURL: 'api',
        timeout: 50000
    });
    myRequest.interceptors.response.use(selfInterceptorsResponse,selfInterceptorsError)
    let result = await( myRequest(config) as MyResponse<T>)
    return result.data
};

const requestsWithoutToken = async <T>(config?: any) => {
    const myRequest = axios.create({
        baseURL: 'api',
        timeout: 50000
    });
    myRequest.interceptors.response.use(selfInterceptorsResponse,selfInterceptorsError)
    let result = await( myRequest(config) as MyResponse<T>)
    return result.data
};

const amap = axios.create({
    baseURL:"https://restapi.amap.com/v3",
    params:{
        key:'8c895014d17b199ba982198ca1c53a10',
        coordsys:'gps'
    }
})
const requestIsSuccess=(result:AxiosResponse<ServerResponse<any>>)=>{
    return result.status==200&&result.data.state==200
}
const requestGetData=(result:ServerResponse)=>{
    return result.data.data
}
const requestGetError=(error:HttpResponse)=>{
    return error.config.url+" error";//todo显示错误信息
}
const requestGetServerMessage=(result:AxiosResponse<ServerResponse<any>>)=>{
    return result.data.msg
}
export {requests,amap,requestsWithoutToken,requestsLongtime,requestIsSuccess,requestGetData};